package com.demo.jpa.service;

import com.demo.jpa.dao.entity.UserEntity;
import com.demo.jpa.dao.repository.UserRepository;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.concurrent.ListenableFuture;

import javax.transaction.Transactional;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author:liaoyoule
 * @Description 不同的返回类型
 * @Date: Created in 15:23 2018/7/20
 * @Modifyied By:
 */
@Log4j2
public class DifferentReturnType extends TestCase {
    @Autowired
    private UserRepository userService;

    /**
     * stream 的返回方式
     */
    @Test
    @Transactional
    public void streamReturn() {
        List<Integer> inIds = Stream.of(1, 2).collect(Collectors.toList());
        UserEntity userEntity = userService.findByUidIn(inIds).findFirst().get();
        log.info("用户：{}", userEntity);
    }

    @Test
    @SneakyThrows
    public void futureReturn() {
        log.info("查询开始===");
        Future<UserEntity> future = userService.findByUid(1);
        log.info("查询结束=== {}", future.isDone());
        UserEntity userEntity = future.get();
        log.info("用户：{}", userEntity);
    }

    @Test
    @SneakyThrows
    public void completableFutureReturn() {
        log.info("查询开始===");
        CompletableFuture<UserEntity> future = userService.findOneByUid(1);
        log.info("查询结束=== {}", future.isDone());
        UserEntity userEntity = future.get();
        log.info("用户：{}", userEntity);
    }


    @Test
    @SneakyThrows
    public void listenableFutureReturn() {
        log.info("查询开始===");
        ListenableFuture<UserEntity> future = userService.queryByUid(1);
        future.addCallback(userEntity -> log.info("哈哈我成功了 {}", userEntity), throwable -> log.info("eem 怎么又失败了 {}", ExceptionUtils.getStackFrames(throwable)));
        log.info("查询结束=== {}", future.isDone());
        future.get();
    }

}
